home *** CD-ROM | disk | FTP | other *** search
/ MacHack 1998 / MacHack 1998.toast / Sessions / Why Java Sucks / Newton11 / TickerThread.java < prev   
Encoding:
Text File  |  1998-03-13  |  1.5 KB  |  102 lines  |  [TEXT/R*ch]

  1. /*
  2.     TickerThread.java - A timer thread class for running periodic tasks.
  3.  
  4.     Copyright (C) 1996-1997 by Michael J. Webb
  5. */
  6.  
  7. // Imports
  8.  
  9. import IdleTask;
  10.  
  11. /** Timer thread class for running periodic tasks.
  12.  */
  13. class TickerThread extends Thread
  14. {
  15. /* Construction/Destruction Methods. */
  16.  
  17.     /** Main constructor; takes an object with an idle task.
  18.      */
  19.     public TickerThread(IdleTask idleObject)
  20.     {
  21.         setDaemon(true);
  22.         kickMe = idleObject;
  23.     }
  24.  
  25.     /** Timed constructor; takes an object with a periodic task and a sleep time.
  26.      */
  27.     public TickerThread(IdleTask idleObject, int sleepTime)
  28.     {
  29.         this(idleObject);
  30.         fSleepTime = sleepTime;
  31.     }
  32.  
  33. /* Public Methods. */
  34.  
  35.     /** The body of this thread.
  36.      */
  37.     public void run()
  38.     {
  39.         // Twiddle thumbs for a second so the UI can stabilize.
  40.  
  41.         try
  42.         {
  43.             sleep(1000);
  44.         }
  45.         catch (Throwable e)
  46.         {
  47.         }
  48.  
  49.         // Run the idle task of the dependent object and then take a nap.
  50.  
  51.         while (true)
  52.         {
  53.             try
  54.             {
  55.                 synchronized (this)
  56.                 {
  57.                     kickMe.idle();
  58.                 }
  59.         
  60.                 snooze();
  61.             }
  62.             catch (Throwable e)
  63.             {
  64.                 System.err.println(e.toString());
  65.                 e.printStackTrace(System.err);
  66.             }
  67.         }
  68.     }
  69.  
  70. /* Private Members. */
  71.  
  72.     /** The dependent task.
  73.      */
  74.     private IdleTask kickMe;
  75.  
  76.     /** Task periodicity.
  77.      */
  78.     private int fSleepTime = 0;
  79.  
  80. /* Private methods. */
  81.  
  82.     /** Yield time to other threads.  If this is a periodic task, also
  83.         sleep for a given amount of time.
  84.      */
  85.     private void snooze()
  86.     {
  87.         try
  88.         {
  89.             if (fSleepTime > 0)
  90.             {
  91.                 sleep(fSleepTime);
  92.             }
  93.  
  94.             yield();
  95.         }
  96.         catch (Throwable e)
  97.         {
  98.         }
  99.     }
  100.  
  101. }
  102.